package com.polaris.live.popup.party

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.party.InvitingSeatAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.network.request
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupInvitingSeatListBinding
import com.polaris.live.net.liveService
import com.polaris.live.viewmodel.party.PartyAnchorFragmentModel

/**
 *  邀请上座列表
 * @author Created by 天晴 on 2024/2/27 19:18
 * @since 1.0.0
 **/
class InvitingSeatListPopup(
    context: Context,
    private val seatId: Int?,
    private val viewModel: PartyAnchorFragmentModel,
    private val objectId: Long,
) : BottomPopupView(context) {
    private lateinit var mBinding: PopupInvitingSeatListBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_inviting_seat_list
    }

    //麦位是否邀请过一次，下次不传麦位id
    private var siteIsInviting = false
    private val mAdapter by lazy {
        InvitingSeatAdapter()
    }
    private val mLayoutManager by lazy {
        LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupInvitingSeatListBinding.bind(popupImplView)

        initView()
        initListener()
        getData()
    }


    private fun initListener() {
        mAdapter.setOnItemChildClickListener { _, view, po ->
            when (view.id) {
                R.id.click_rl -> {
                    showSeatPopup(mAdapter.data[po].userId)
                }
            }
        }
    }

    private fun initView() {
        mBinding.recycler.apply {
            adapter = mAdapter
            layoutManager = mLayoutManager
        }
        mAdapter.setEmptyView(R.layout.widget_inviting_empty)
    }


    fun getData() {
        viewModel.request({ liveService.partyInvitationList(objectId) }, {
            val list = it.filter { user -> user.userId != UserManager.getUserId() }
            mAdapter.addData(list)
        }) {
            ToastGravity.showGravity(it.errorMsg)
        }
    }


    /**
     * 显示座位管理
     */
    private fun showSeatPopup(userId: Long) {
        XPopup.Builder(context)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true)
            .asCustom(InvitingSeatPopup(context) {
                viewModel.partyInviteSite(userId, seatId?.takeIf { !siteIsInviting }, objectId)
            })
            .show()
    }
}